/**
*	@file QueryVarTable.cpp
*
*	@brief this header defines query variable table
*
*	@author li yuchen
*
*	@date 1/28/2011
*/
#include "QueryVarTable.h"

vector<QueryVarEntry*> QueryVarTable::vp_qvar_entries_;

// step1: check duplication
// step2: add var
QueryVarIdx QueryVarTable::InsertQueryVar(QueryVarName qvar_name, TNodeType qvar_type)
{
	// check duplication
	QueryVarEntry* vp_qvar_entry_temp = NULL;
	if( CheckQueryVarNameExistence(qvar_name, &vp_qvar_entry_temp) )
	{
		cout << "cannot have duplicate declaration of query variables " << endl;
		return -1;
	}

	// add var
	vp_qvar_entry_temp = new QueryVarEntry;
	vp_qvar_entry_temp->qvar_idx = vp_qvar_entries_.size()+1;
	vp_qvar_entry_temp->qvar_name = qvar_name;
	vp_qvar_entry_temp->qvar_type = qvar_type;

	vp_qvar_entries_.push_back(vp_qvar_entry_temp);

	return vp_qvar_entry_temp->qvar_idx;
}


QueryVarIdx QueryVarTable::GetQueryVarIdx(QueryVarName qvar_name)
{
	QueryVarEntry* vp_qvar_entry_temp = NULL;
	if( CheckQueryVarNameExistence(qvar_name, &vp_qvar_entry_temp) )
		return vp_qvar_entry_temp->qvar_idx;
	return -1;
}
	
QueryVarName QueryVarTable::GetQueryVarName(QueryVarIdx qvar_idx)
{
	return GetQueryVarEntry(qvar_idx)->qvar_name;
}

TNodeType QueryVarTable::GetQueryVarType(QueryVarIdx qvar_idx)
{
	return GetQueryVarEntry(qvar_idx)->qvar_type;
}

string QueryVarTable::ToString()
{
	stringstream ss_result;
	ss_result << "QueryVarTable :\n";
	for(int i = vp_qvar_entries_.size(); i>0; i--)
	{
		ss_result << vp_qvar_entries_[i-1]->qvar_idx << " : " << vp_qvar_entries_[i-1]->qvar_name << " , "<< vp_qvar_entries_[i-1]->qvar_type << endl;
	}
	return ss_result.str();
}


void QueryVarTable::ClearQueryVarTable()
{
	vp_qvar_entries_.clear();
}


QueryVarEntry* QueryVarTable::GetQueryVarEntry(QueryVarIdx qvar_idx)
{
	return vp_qvar_entries_[qvar_idx-1];
}

// step1: try to retrieve data from linked list
// step2: try to retrieve data from array
bool QueryVarTable::CheckQueryVarNameExistence(QueryVarName qvar_name, QueryVarEntry** vp_qvar_entry)
{
	vector<QueryVarEntry*>::iterator iter_p_qvar_entry;
	for(iter_p_qvar_entry = vp_qvar_entries_.begin();
		iter_p_qvar_entry != vp_qvar_entries_.end();
		iter_p_qvar_entry++)
	{
		if((*iter_p_qvar_entry)->qvar_name.compare(qvar_name) == 0)
		{
			*vp_qvar_entry = *iter_p_qvar_entry;
			return true;
		}
	}
	return false;
}
